#include "../../include/pagelib/DirScanner.h"
#include "../../include/pagelib/MyLogger.h"

#include <filesystem>
#include <pthread.h>

namespace fs = std::filesystem;

DirScanner *DirScanner::_pInstance = nullptr;
pthread_once_t DirScanner::_once = PTHREAD_ONCE_INIT;

DirScanner* DirScanner::getInstance()
{
    pthread_once(&_once,init_r);
    return _pInstance;
}

// 返回文件列表
vector<string>& DirScanner::getFiles()
{
    if (_files.empty())
    {
        LogError("_files is empty!");
        static vector<string> emptyVec;
        return emptyVec;
    }
    return _files;
}

// 遍历目录的入口函数
void DirScanner::scan(const string &dirname)
{
    traverse(fs::path(dirname));
}

// 获取某一目录下的所有文件
void DirScanner::traverse(const string &dirname)
{
    try
    {
        for(const auto& entry:fs::directory_iterator(dirname))
        {
            if(fs::is_directory(entry))
            {
                traverse(entry.path());  // 递归遍历子目录
            }
            else if(fs::is_regular_file(entry))
            {
                _files.push_back(entry.path().string());  // 添加文件路径
            }
        }
    }
    catch(const fs::filesystem_error& e)
    {
        LogError("Error: "+e.what());
        return ;
    }
}

DirScanner::DirScanner()
{

}
DirScanner::~DirScanner()
{

}

void DirScanner::init_r()
{
    if(_pInstance == nullptr)
    {
        _pInstance = new DirScanner();
        atexit(destory);
    }
}

void DirScanner::destory()
{
    if(_pInstance)
    {
        delete _pInstance;
        _pInstance = nullptr;
    }
}








